
package com.wzapp.sitposture.common.converter;

import com.alibaba.fastjson.JSONArray;
import com.wzapp.sitposture.common.util.ToolUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.AttributeConverter;
import java.io.IOException;

/**
 * 功能: 将对象属性转换为JSON字符串，保存数据库；或者从数据库读取json转为对象. <br/>
 * 日期: 2017年12月19日 下午3:07:02 <br/>
 * 
 * @author wzj
 * @version
 * @since JDK 1.8
 */
public class JsonArrayConverterJson implements AttributeConverter<JSONArray, String> {

	private static final Logger log = LoggerFactory.getLogger(JsonArrayConverterJson.class);

	private final static ObjectMapper objectMapper = new ObjectMapper();

	@Override
	public String convertToDatabaseColumn(JSONArray meta) {
        if (ToolUtil.isEmpty(meta)){
            return "";
        }
		try {
			if(ToolUtil.isNotEmpty(meta)){

				return objectMapper.writeValueAsString(meta);
			}
			return null;
		} catch (JsonProcessingException ex) {
			log.error("JpaConverterJson convertToDatabaseColumn error." + ex.getMessage());
			return null;
		}
	}

	@Override
	public JSONArray convertToEntityAttribute(String dbData) {
		if (ToolUtil.isEmpty(dbData)){
			return null;
		}
		try {
			if(ToolUtil.isNotEmpty(dbData)){
				return objectMapper.readValue(dbData, JSONArray.class);
			}
			return null;
		} catch (IOException ex) {
			log.error("JpaConverterJson decoding json from database error." + dbData);
			return null;
		}
	}

}